<!-- eslint-disable no-console -->
<!-- 质量管理模块 - 常见缺陷 -->
<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form';
import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table';
import type { DictApi, QcdefectApi, ToolTypeApi } from '#/api';

import { reactive, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { VxeButton } from '@vben/plugins/vxe-table';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteQcdefect, DictResp, getQcdefectList } from '#/api';
import { getToolBarBtns, setToolBarBtnDefaultDisabled } from '#/utils/toolbar';

import { confirm, messageError, messageSuccess } from '../../wm/common/common';
import editModal from './edit-modal.vue';
// import {} from 'element-plus';
// 将字典数据添加到数组中;
const mes_index_type = reactive<DictApi.SelectOption[]>([]);
const mes_defect_level = reactive<DictApi.SelectOption[]>([]);
DictResp(['mes_index_type', 'mes_defect_level']).then((res) => {
  // 将两个数组合并
  if (res.mes_index_type) {
    mes_index_type.push(...res.mes_index_type);
    // const mesindex = mes_index_type.map((item) => ({ value: item.value }));
    // console.log(mesindex);
  }
  if (res.mes_defect_level) {
    mes_defect_level.push(...res.mes_defect_level);
  }
});

// 存储选中行的响应式变量
const selectedRows = ref<ToolTypeApi.Row[]>([]);
const initData = {
  toolTypeId: null,
  toolTypeCode: '',
  toolTypeName: '',
  codeFlag: 'Y',
  maintenType: null,
  maintenPeriod: null,
  remark: '',
};
selectedRows.value = [initData];

const [EditModal, editmodalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: editModal,
});

const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入缺陷描述',
      },
      fieldName: 'defectName',
      label: '缺陷描述',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: mes_defect_level,
        placeholder: '请选择缺陷等级',
      },
      fieldName: 'defectLevel',
      label: '缺陷等级',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: mes_index_type,
        placeholder: '请选择检测项类型',
      },
      fieldName: 'indexType',
      label: '检测项类型',
    },
  ],
  // 控制表单是否显示折叠按钮
  showCollapseButton: false,
  submitButtonOptions: {
    content: '搜索',
  },
  // 是否在字段值改变时提交表单
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: false,
};

// 表格左上角按钮
const buttons = getToolBarBtns();
const gridOptions: VxeGridProps<QcdefectApi.Row> = {
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
  },
  columns: [
    {
      align: 'left',
      field: 'defectId',
      title: '',
      type: 'checkbox',
      width: 50,
    },
    { field: 'defectName', title: '缺陷描述' },
    {
      field: 'indexType',
      title: '检测项类型',
      formatter: ({ cellValue }) => {
        const item = mes_index_type.find((item) => item.value === cellValue);
        return item?.label || '无';
      },
    },
    {
      field: 'defectLevel',
      title: '缺陷等级',
      formatter: ({ cellValue }) => {
        const item = mes_defect_level.find((item) => item.value === cellValue);
        return item?.label || '无';
      },
    },
    { slots: { default: 'action' }, title: '操作' },
  ],
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        const res = await getQcdefectList({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
        return {
          total: res.total,
          items: res.rows,
        };
      },
    },
  },

  toolbarConfig: {
    // 是否显示搜索表单控制按钮
    // @ts-ignore 正式环境时有完整的类型声明
    search: true,
    custom: true,
    zoom: true,
    refresh: { code: 'query' },
    buttons: buttons.value,
  },
};

const gridEvents: VxeGridListeners = {
  toolbarButtonClick({ code }) {
    switch (code) {
      case 'myAdd': {
        // 新增逻辑
        console.log('新增');
        editmodalApi
          .setState({
            title: '新增常见缺陷',
          })
          .setData({ mes_index_type, mes_defect_level })
          .open();
        break;
      }
      case 'myDel': {
        // 删除逻辑
        console.log('删除');
        deleteRowEvent(selectedRows.value as any);
        break;
      }
      case 'mySave': {
        // 保存逻辑
        console.log('保存');
        break;
      }
      default: {
        break;
      }
    }
  },
  checkboxChange({ records }) {
    selectedRows.value = records;
    setToolBarBtnDefaultDisabled(buttons, records.length);
  },
  checkboxAll({ records }) {
    selectedRows.value = records;
    setToolBarBtnDefaultDisabled(buttons, records.length);
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents,
});

function editRowEvent(row: QcdefectApi.Row) {
  // console.log(row);
  editmodalApi
    .setState({
      title: '修改常见缺陷',
    })
    .setData({ row, mes_index_type, mes_defect_level })
    .open();
  gridApi.grid?.setEditRow(row);
}
function deleteRowEvent(row: QcdefectApi.Row) {
  const ids = Array.isArray(row)
    ? row.map((item) => item.defectId)
    : [row.defectId];
  const idString = ids.join(',');
  confirm(`确定要删除常见缺陷编号为${idString}的数据吗？`, '提示').then(() => {
    deleteQcdefect(idString)
      .then(() => {
        messageSuccess(`删除成功`);
        refreshGrid();
      })
      .catch((error) => {
        messageError(error);
      });
  });
}

function refreshGrid() {
  gridApi.query();
}
</script>

<template>
  <div>
    <EditModal @success="refreshGrid" />
    <Grid>
      <template #action="{ row }">
        <VxeButton
          mode="text"
          icon="vxe-icon-signature"
          @click="editRowEvent(row)"
          status="primary"
        >
          编辑
        </VxeButton>
        <VxeButton
          icon="vxe-icon-delete"
          mode="text"
          @click="deleteRowEvent(row)"
          status="error"
        >
          删除
        </VxeButton>
      </template>
    </Grid>
  </div>
</template>
